﻿using CoreEx.Common.Proxy;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;
using LinFu.Proxy.Interfaces;


namespace CoreEx.Database.Client.Implementation
{
    
    /// <summary>
    /// Creates an <see cref="IProxy"/> instance for a target instance of <typeparamref name="T"/>.
    /// </summary>
    /// <typeparam name="T">The actual target instance type.</typeparam>
    public class ProxyFactory<T> : IProxyFactory<T>, IInitialize
    {
        
        protected IServiceContainer _serviceContainer;

        protected IProxyFactory _proxyFactory;
                
        #region IInitialize<IServiceContainer> Members

        public void Initialize(IServiceContainer source)
        {
            _serviceContainer = source;
            _proxyFactory = source.GetService<IProxyFactory>();
        }

        #endregion

        #region IProxyFactory<T> Members

        /// <summary>
        /// Creates a <see cref="IProxy"/> instance for the <paramref name="actualTarget"/>.
        /// </summary>
        /// <param name="actualTarget">The actual target instance.</param>
        /// <returns>An <see cref="IProxy"/> instance that implements the <typeparamref name="T"/> interface.</returns>
        public virtual T CreateProxy(T actualTarget)
        {                        
            return _proxyFactory.CreateProxy<T>(_serviceContainer.GetService<IInvokeWrapper<T>>(actualTarget), typeof(IActualTarget));
        }
                
        #endregion
    }
}
